package com.ohc.leetcode.栈;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class 有效的括号20 {
    public static boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        int length = s.length();
        if (length % 2 == 1) {
            return false;
        }
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();

        boolean flag = true;
        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])) {
                stack.push(chars[i]);
            } else {
                if (map.containsValue(chars[i])) {
                    if (stack.empty()) {
                        return false;
                    }
                    Character pop = stack.pop();

                    if (!map.get(pop).equals(chars[i])) {
                        return false;

                    }
                }
            }
        }
        return stack.empty();
    }

    public static void main(String[] args) {
        String str = "(())";
        boolean valid = isValid(str);
        System.out.println("valid = " + valid);
    }
}
